package database

import (
	"database/sql"
)

// statement struct
type Statement struct {
	sqlStmt *sql.Stmt
	QueryString   string
	isPanic       bool
}

// query by statement with args
func (this *Statement) Query(args...interface {}) ([]map[string]string, error) {
	rows, e := this.sqlStmt.Query(args...)
	if e != nil {
		return nil, panicError(this.isPanic, this.QueryString, e)
	}
	defer rows.Close()
	rs, e2 := rowMapper(rows)
	return rs, panicError(this.isPanic, this.QueryString, e2)
}

// query one rows by statement with args
func (this *Statement) One(args... interface {}) (map[string]string, error) {
	rs, e := this.Query(args...)
	if e != nil {
		return nil, e
	}
	if len(rs) < 1 {
		return nil, nil
	}
	return rs[0], nil
}

// execute sql by statement with args
func (this *Statement) Exec(args... interface {}) (int64, error) {
	rs , e := this.sqlStmt.Exec(args...)
	if e != nil {
		return -1, panicError(this.isPanic, this.QueryString, e)
	}
	var i int64
	i, e = resultParser(rs)
	return i, panicError(this.isPanic, this.QueryString, e)
}

// close statement
func (this *Statement) Close() {
	this.sqlStmt.Close()
}

// get raw *sql.Stmt struct
func (this *Statement) SqlStmt()*sql.Stmt{
	return this.sqlStmt
}

